package response

import (
	"admin-system/pkg/error_code"
	"github.com/gin-gonic/gin"
	"net/http"
)

type Response struct {
	Code    int64       `json:"code"`
	Message string      `json:"message"`
	Data    interface{} `json:"data,omitempty"` // 增加 omitempty 避免输出 null
}

// NewResponse 构造一个响应对象，用于统一响应格式
func NewResponse(code int64, message string, data interface{}) Response {
	return Response{
		Code:    code,
		Message: message,
		Data:    data,
	}
}

func Success(c *gin.Context, data interface{}) {
	resp := NewResponse(error_code.SUCCESS, "success", data)
	httpCode := http.StatusOK
	c.JSON(httpCode, resp)
}

func Fail(c *gin.Context, code int64, msg string) {

	resp := NewResponse(code, msg, nil)
	httpCode := http.StatusOK

	// 根据错误码映射合适的 HTTP 状态码
	switch {
	case code >= 400 && code < 500:
		httpCode = http.StatusBadRequest
	case code >= 500:
		httpCode = http.StatusInternalServerError
	default:
		httpCode = http.StatusOK
	}

	c.JSON(httpCode, resp)
}
